import tkinter as tk
from tkinter import messagebox
import random
import time

class GuessNumberGUI:
    def __init__(self, master: tk.Tk):
        self.master = master
        master.title("猜数字 0-99")
        master.resizable(False, False)

        self.answer = random.randint(0, 99)
        self.start_time = time.time()
        self.count = 0
        self.game_over = False

        # ---------- 界面元素 ----------
        tk.Label(master, text="请输入 0-99 之间的整数：", font=(None, 14)).pack(pady=10)

        self.entry = tk.Entry(master, font=(None, 16), width=8, justify="center")
        self.entry.pack()
        self.entry.focus()

        tk.Button(master, text="确定", command=self.check, font=(None, 12), width=10).pack(pady=8)

        self.hint = tk.StringVar()
        self.hint.set("开始猜数字吧！")
        tk.Label(master, textvariable=self.hint, font=(None, 12), fg="blue").pack(pady=6)

        self.time_label = tk.StringVar()
        self.update_timer()          # 启动实时计时器
        tk.Label(master, textvariable=self.time_label, font=(None, 10)).pack(side="right", padx=10, pady=5)

        # 回车绑定
        master.bind("<Return>", lambda e: self.check())

    # ---------- 逻辑 ----------
    def check(self):
        if self.game_over:
            return
        try:
            guess = int(self.entry.get())
        except ValueError:
            messagebox.showwarning("提示", "请输入合法整数！")
            self.entry.delete(0, tk.END)
            return

        if not 0 <= guess <= 99:
            messagebox.showwarning("提示", "数字必须在 0-99 之间！")
            return

        self.count += 1
        if guess > self.answer:
            self.hint.set("猜大了，再试一次")
        elif guess < self.answer:
            self.hint.set("猜小了，加油吧")
        else:
            self.game_over = True
            elapsed = round(time.time() - self.start_time, 2)
            msg = f"回答正确！\n共猜 {self.count} 次，耗时 {elapsed} 秒"
            messagebox.showinfo("恭喜", msg)
            if messagebox.askyesno("再来一局", "是否重新开始？"):
                self.restart()
            else:
                self.master.quit()
        self.entry.delete(0, tk.END)

    # ---------- 辅助 ----------
    def update_timer(self):
        if not self.game_over:
            t = round(time.time() - self.start_time, 1)
            self.time_label.set(f"计时: {t} 秒")
            self.master.after(100, self.update_timer)

    def restart(self):
        self.answer = random.randint(0, 99)
        self.start_time = time.time()
        self.count = 0
        self.game_over = False
        self.hint.set("重新开始，祝你好运！")
        self.entry.delete(0, tk.END)
        self.entry.focus()
        self.update_timer()

# ---------- 入口 ----------
if __name__ == "__main__":
    root = tk.Tk()
    GuessNumberGUI(root)
    root.mainloop()